package com.gitee.huxing.framework.core;

import com.alibaba.fastjson.JSON;
import com.gitee.huxing.framework.core.filter.Filter;
import com.gitee.huxing.framework.core.module.RequestInfo;
import com.gitee.huxing.framework.core.module.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import java.io.IOException;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.framework.core
 * @ClassName: AbstractInvokeHandler
 * @Author: huxing
 * @DateTime: 2021-10-03 下午11:40
 */
@Slf4j
public class AbstractInvokeHandler {

    /** 默认请求参数类型 **/
    public static final MediaType JSON_TYPE = MediaType.get("application/json; charset=utf-8");

    /** 请求服务类 **/
    protected final Class<?> serviceClass;

    /** 请求地址 **/
    protected final String url;

    /** 过滤器 **/
    protected final Filter[] filters;

    public <T> AbstractInvokeHandler(Class<T> serviceClass, String url, Filter[] filters) {
        this.serviceClass = serviceClass;
        this.url = url;
        this.filters = filters;
    }

    /**
     * @Description: 调用http服务发送请求记录
     * @Author: huxing
     * @param requestInfo
     * @param url
     * @return com.gitee.huxing.framework.core.module.ResponseInfo
     * @Date: 2021/9/30 上午10:02
     **/
    protected ResponseInfo post(RequestInfo requestInfo, String url) throws IOException {
        // 请求对象转json字符串
        String reqJson = JSON.toJSONString(requestInfo);
        log.info("request json: {}", reqJson);
        // 调用http client发送记录
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(JSON_TYPE, reqJson))
                .build();
        // 调用请求
        String respJson = client.newCall(request).execute().body().string();
        log.info("response json: {}", respJson);
        // 返回http请求结果
        return JSON.parseObject(respJson, ResponseInfo.class);
    }
}
